<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="商家名称" prop="merchantId">
        <el-select 
          v-model="queryParams.merchantId" 
          placeholder="请选择商家" 
          filterable 
          :loading="merchantLoading"
          class="!w-240px"
          popper-class="account-select-dropdown"
          clearable
          @focus="handleSelectFocus"
          @visible-change="handleVisibleChange"
          @filter-method="handleSearch"
        >
          <el-option
            v-for="item in merchantList"
            :key="item.id"
            :label="item.merchantName"
            :value="item.id"
          />
          <template #dropdown>
            <div class="merchant-select-content">
              <div v-if="merchantList.length === 0" class="merchant-empty">
                <el-empty description="暂无数据" />
              </div>
              <div v-if="hasMore && !merchantLoading" class="merchant-loading">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span class="loading-text">加载更多...</span>
              </div>
            </div>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="账户类型" prop="accountType">


        <el-select
          v-model="queryParams.accountType"
          placeholder="请选择账户类型"
          clearable
          class="!w-240px"
        >

          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.JULIANG_ACCOUNT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    
     
    
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
  
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['juliang:account-balance:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['juliang:account-balance:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">

      <el-table-column label="商家名称" align="center" prop="merchantName" />
      <el-table-column label="账户类型" align="center" prop="accountType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.JULIANG_ACCOUNT_TYPE" :value="scope.row.accountType" />
        </template>
      </el-table-column>
      <el-table-column label="巨量账户ID" align="center" prop="advertiserId" />
      <el-table-column label="余额" align="center" prop="balance">
        <template #default="scope">
          <span :class="{ 'negative-balance': scope.row.balance < 0 }">
            {{ scope.row.balance }}元
          </span>
        </template>
      </el-table-column>
      <el-table-column label="冻结金额" align="center" prop="frozenAmount" />
      <el-table-column label="折扣类型" align="center" prop="rechargeDiscountType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.JULIANG_RECHARGE_DISCOUNT_TYPE" :value="scope.row.rechargeDiscountType" />
        </template>
      </el-table-column>
      <el-table-column label="比例" align="center" prop="rebateRatio">
        <template #default="scope">
          <span v-if="scope.row.rebateRatio !== null && scope.row.rebateRatio !== undefined">
            {{ scope.row.rebateRatio < 1 ? (scope.row.rebateRatio * 100).toFixed(2) : scope.row.rebateRatio.toFixed(2) }}%
          </span>
          <span v-else>-</span>
         
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
                {{ scope.row.status === 0 ? '正常' : '封禁' }}
              </el-tag>
            </template>
          </el-table-column>

      <el-table-column label="操作" align="center" min-width="240px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['juliang:account-balance:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            @click="openBindDialog(scope.row)"
            v-hasPermi="['juliang:account-balance:update']"
          >
            巨量账号
          </el-button>
          <!-- 数据查询三个操作铺开为按钮 -->
          <el-button link type="primary" @click="handleQueryBalance(scope.row)" v-hasPermi="['juliang:account-balance:query']">余额</el-button>
          <el-button link type="primary" @click="handleQueryDailyFlow(scope.row)" v-hasPermi="['juliang:account-balance:query']">日流水</el-button>
          <el-button link type="primary" @click="handleQueryTransaction(scope.row)" v-hasPermi="['juliang:account-balance:query']">交易明细</el-button>
          <!-- 封禁/解封账户直接显示为按钮 -->
          <el-button
            link
            type="warning"
            @click="handleBanAccount(scope.row)"
            v-hasPermi="['juliang:account-balance:update']"
          >
            {{ scope.row.status === 0 ? '封禁账户' : '解封账户' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AccountBalanceForm ref="formRef" @success="getList" />

  <!-- 绑定抖音账号弹窗 -->
  <Dialog :title="'巨量账号'" v-model="bindDialogVisible">
    <el-form
      ref="bindFormRef"
      :model="bindForm"
      :rules="bindRules"
      label-width="120px"
    >
      <el-form-item label="巨量账户ID" prop="advertiserId">
        <el-input
          v-model="bindForm.advertiserId"
          placeholder="请输入巨量账户ID"
        />
      </el-form-item>
      <el-form-item label="备注">
        <div style="font-size: 14px; color: #909399;">
          请从巨量引擎平台复制账号并绑定。
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="bindDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleBind" :loading="bindLoading">确 定</el-button>
    </template>
  </Dialog>

  <!-- 催款弹窗 -->
  <Dialog :title="'发送催款通知'" v-model="dunningDialogVisible" width="600px">
    <el-form
      ref="dunningFormRef"
      :model="dunningForm"
      :rules="dunningRules"
      label-width="120px"
    >
      <el-form-item label="商家信息">
        <el-input
          :value="`账户ID: ${currentAccount?.id || ''} (余额: ${currentAccount?.balance || 0}元)`"
          disabled
        />
      </el-form-item>
      <el-form-item label="催款方式" prop="dunningType">
        <el-radio-group v-model="dunningForm.dunningType">
          <el-radio :label="1">短信通知</el-radio>
          <el-radio :label="2">邮件通知</el-radio>
          <el-radio :label="3">站内消息</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="催款内容" prop="content">
        <el-input
          v-model="dunningForm.content"
          type="textarea"
          :rows="4"
          placeholder="请输入催款内容"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="备注">
        <div style="font-size: 14px; color: #909399;">
          系统将根据选择的方式向商家发送催款通知。
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dunningDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSendDunning" :loading="dunningLoading">发送催款</el-button>
    </template>
  </Dialog>

  <!-- 查询余额弹窗 -->
  <Dialog :title="'查询余额'" v-model="balanceDialogVisible" width="1500px">
    <div v-loading="balanceLoading">
      <el-descriptions :column="2" border v-if="balanceData">
        <el-descriptions-item label="广告主ID">{{ balanceData.advertiserId }}</el-descriptions-item>
        <el-descriptions-item label="账户名">{{ balanceData.name }}</el-descriptions-item>
        <el-descriptions-item label="联系邮箱">{{ balanceData.email }}</el-descriptions-item>
        <el-descriptions-item label="账户总余额">{{ balanceData.balance }}元</el-descriptions-item>
        <el-descriptions-item label="账户可用总余额">{{ balanceData.validBalance }}元</el-descriptions-item>
        <el-descriptions-item label="现金余额">{{ balanceData.cash }}元</el-descriptions-item>
        <el-descriptions-item label="现金可用余额">{{ balanceData.validCash }}元</el-descriptions-item>
        <el-descriptions-item label="赠款余额">{{ balanceData.grant }}元</el-descriptions-item>
        <el-descriptions-item label="赠款可用余额">{{ balanceData.validGrant }}元</el-descriptions-item>
        <el-descriptions-item label="默认广告位可用赠款">{{ balanceData.defaultGrant }}元</el-descriptions-item>
        <el-descriptions-item label="通用广告位可用赠款">{{ balanceData.commonGrant }}元</el-descriptions-item>
        <el-descriptions-item label="搜索广告位可用赠款">{{ balanceData.searchGrant }}元</el-descriptions-item>
        <el-descriptions-item label="穿山甲广告位可用赠款">{{ balanceData.unionGrant }}元</el-descriptions-item>
        <el-descriptions-item label="钱包ID">{{ balanceData.walletId }}</el-descriptions-item>
        <el-descriptions-item label="钱包名称">{{ balanceData.walletName }}</el-descriptions-item>
        <el-descriptions-item label="子钱包可用共享余额">{{ balanceData.walletTotalBalanceValid }}元</el-descriptions-item>
      </el-descriptions>
      <div v-else style=" padding: 20px;text-align: center;">
        暂无数据
      </div>
    </div>
    <template #footer>
      <el-button @click="balanceDialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>

  <!-- 查询日流水弹窗 -->
  <Dialog :title="'查询日流水'" v-model="dailyFlowDialogVisible" width="1500px">
    <el-form
      ref="dailyFlowFormRef"
      :model="dailyFlowForm"
      :rules="dailyFlowRules"
      label-width="120px"
      style="margin-bottom: 20px;"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="dailyFlowForm.startDate"
              type="date"
              placeholder="选择开始日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="dailyFlowForm.endDate"
              type="date"
              placeholder="选择结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="账户业务类型" prop="accountType">
            <el-select v-model="dailyFlowForm.accountType" placeholder="请选择账户业务类型" style="width: 100%">
              <el-option label="AD（默认）" value="AD" />
              <el-option label="LOCAL" value="LOCAL" />
              <el-option label="STAR" value="STAR" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="queryDailyFlow" :loading="dailyFlowLoading">查询</el-button>
            <el-button @click="resetDailyFlowForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <el-table v-loading="dailyFlowLoading" :data="dailyFlowData.list" stripe>
      <el-table-column prop="advertiserId" label="广告主ID" />
      <el-table-column prop="date" label="日期" />
      <el-table-column prop="balance" label="日终结余(元)" />
      <el-table-column prop="cashCost" label="现金支出(元)" />
      <el-table-column prop="cost" label="总支出(元)" />
      <el-table-column prop="income" label="总存入(元)" />
      <el-table-column prop="rewardCost" label="赠款支出(元)" />
      <el-table-column prop="transferIn" label="总转入(元)" />
      <el-table-column prop="transferOut" label="总转出(元)" />
      <el-table-column prop="frozen" label="冻结(元)" />
    </el-table>
    
    <Pagination
      :total="dailyFlowData.total"
      v-model:page="dailyFlowForm.page"
      v-model:limit="dailyFlowForm.pageSize"
      @pagination="handleDailyFlowPagination"
    />
    
    <template #footer>
      <el-button @click="dailyFlowDialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>

  <!-- 查询交易明细弹窗 -->
  <Dialog :title="'查询交易明细'" v-model="transactionDialogVisible" width="1500px">
    <el-form
      ref="transactionFormRef"
      :model="transactionForm"
      :rules="transactionRules"
      label-width="120px"
      style="margin-bottom: 20px;"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="transactionForm.startDate"
              type="date"
              placeholder="选择开始日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="transactionForm.endDate"
              type="date"
              placeholder="选择结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="交易类型" prop="transactionType">
            <el-select v-model="transactionForm.transactionType" placeholder="请选择交易类型" style="width: 100%">
              <el-option label="RECHARGE（充值）" value="RECHARGE" />
              <el-option label="TRANSFER（转账）" value="TRANSFER" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="queryTransaction" :loading="transactionLoading">查询</el-button>
            <el-button @click="resetTransactionForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <el-table v-loading="transactionLoading" :data="transactionData.list" stripe>
      <el-table-column prop="advertiserId" label="广告主ID" min-width="150px" />
      <el-table-column prop="transactionType" label="流水类型" />
      <el-table-column prop="createTime" label="流水产生时间" width="180" />
      <el-table-column prop="amount" label="交易总金额(元)" />
      <el-table-column prop="cash" label="现金总金额(元)" />
      <el-table-column prop="grant" label="赠款总金额(元)" />
      <el-table-column prop="returnGoods" label="返货总金额(元)" />
      <el-table-column prop="transactionSeq" label="交易流水号" min-width="180px" />
      <el-table-column prop="remitter" label="付款方" min-width="160px" />
      <el-table-column prop="payee" label="收款方" min-width="160px" />
    </el-table>
    
    <Pagination
      :total="transactionData.total"
      v-model:page="transactionForm.page"
      v-model:limit="transactionForm.pageSize"
      @pagination="handleTransactionPagination"
    />
    
    <template #footer>
      <el-button @click="transactionDialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AccountBalanceApi, AccountBalanceVO } from '@/api/juliang/accountbalance'
import { MerchantVO } from '@/api/juliang/merchant'

// 聚亮余额查询结果类型
interface JuliangBalanceVO {
  advertiserId: number
  name: string
  email: string
  balance: number
  validBalance: number
  cash: number
  validCash: number
  grant: number
  defaultGrant: number
  commonGrant: number
  searchGrant: number
  unionGrant: number
  validGrant: number
  returnGoodsAbs?: number
  validReturnGoodsAbs?: number
  returnGoodsCost?: number
  returnGoodsGrant?: number
  compensationGrant?: number
  returnGoodsValidGrant?: number
  compensationValidGrant?: number
  walletId: string
  walletName: string
  walletTotalBalanceValid: number
}
import AccountBalanceForm from './AccountBalanceForm.vue'

import { createImageViewer } from '@/components/ImageViewer'
import { Loading, ArrowDown } from '@element-plus/icons-vue'
import { throttle, debounce } from 'lodash-es'


/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

    
/** 账户余额 列表 */
defineOptions({ name: 'AccountBalance' })

const message = useMessage() // 消息弹窗

const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AccountBalanceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  merchantId: undefined as number | undefined,
  accountType: undefined as number | undefined,
  accountId: undefined as string | undefined,
  balance: undefined as number | undefined,
  frozenAmount: undefined as number | undefined,
  createTime: [] as string[],
  status: undefined as number | undefined,
  rechargeDiscountType: undefined as number | undefined,
  rebateRatio: undefined as number | undefined,
  queryBeikuanAccount: false,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const merchantList = ref<MerchantVO[]>([]) // 商家列表
const merchantLoading = ref(false) // 商家列表加载状态
const hasMore = ref(true) // 是否还有更多数据
const loadingNewPage = ref(false) // 标记是否正在加载新页面
const searchKeyword = ref('') // 搜索关键字

const merchantQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  merchantName: undefined as string | undefined
})

/** 获取商家列表 */
const getMerchantList = async (isLoadMore = false) => {
  if (merchantLoading.value || (isLoadMore && !hasMore.value)) return
  
  if (isLoadMore) {
    loadingNewPage.value = true
  } else {
    merchantLoading.value = true
  }

  try {
    const data = await AccountBalanceApi.getMerchantPage({
      pageNo: merchantQuery.pageNo,
      pageSize: merchantQuery.pageSize,
      merchantName: searchKeyword.value
    })
    
    if (data?.list?.length > 0) {
      merchantList.value = isLoadMore 
        ? [...merchantList.value, ...data.list]
        : data.list
      hasMore.value = data.list.length === merchantQuery.pageSize
    } else {
      if (!isLoadMore) {
        merchantList.value = []
      }
      hasMore.value = false
    }
  } catch (error) {
    console.error('获取商家列表失败:', error)
    message.error('获取商家列表失败')
    if (!isLoadMore) {
      merchantList.value = []
    }
  } finally {
    merchantLoading.value = false
    loadingNewPage.value = false
  }
}

/** 监听下拉框滚动 */
const handleDropdownScroll = throttle(async (e: Event) => {
  const target = e.target as HTMLElement
  const { scrollTop, scrollHeight, clientHeight } = target
  
  // 距离底部50px时预加载下一页
  if (scrollHeight - scrollTop - clientHeight < 50 && hasMore.value && !loadingNewPage.value) {
    merchantQuery.pageNo++
    await getMerchantList(true)
  }
}, 200)

/** 处理下拉框显示状态变化 */
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 下拉框显示时，添加滚动监听
    nextTick(() => {
      const dropdownWrapper = document.querySelector('.account-select-dropdown .el-select-dropdown__wrap')
      if (dropdownWrapper) {
        dropdownWrapper.addEventListener('scroll', handleDropdownScroll)
      }
    })
  } else {
    // 下拉框隐藏时，移除滚动监听
    const dropdownWrapper = document.querySelector('.account-select-dropdown .el-select-dropdown__wrap')
    if (dropdownWrapper) {
      dropdownWrapper.removeEventListener('scroll', handleDropdownScroll)
    }
  }
}

/** 处理搜索 */
const handleSearch = debounce((query: string) => {
  searchKeyword.value = query.trim()
  merchantQuery.pageNo = 1
  hasMore.value = true
  merchantList.value = []
  getMerchantList()
}, 300)

/** 处理下拉框获得焦点 */
const handleSelectFocus = () => {
  if (merchantList.value.length === 0) {
    searchKeyword.value = ''
    merchantQuery.pageNo = 1
    hasMore.value = true
    getMerchantList()
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AccountBalanceApi.getAccountBalancePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  // 处理返利比例搜索条件转换
  if (queryParams.rebateRatio !== null && queryParams.rebateRatio !== undefined) {
    const rebateValue = parseFloat(queryParams.rebateRatio.toString()) / 100
    queryParams.rebateRatio = rebateValue
  }
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  // 重置商家相关的状态
  merchantList.value = []
  hasMore.value = true
  merchantQuery.pageNo = 1
  searchKeyword.value = ''
  // 重置新增的查询字段
  queryParams.rechargeDiscountType = undefined
  queryParams.rebateRatio = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AccountBalanceApi.deleteAccountBalanceById(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}


/** 修改状态 */
const handleStatusChange = async (row: AccountBalanceVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要' + text + '该账户余额记录吗?')
    // 发起修改状态
    const res = await AccountBalanceApi.updateAccountBalanceStatus(row.id, row.status)
    
    if (res.code === 0) {
      message.success(`${text}成功`)
      // 刷新列表
      await getList()
    } else {
      message.error(res.msg || `${text}失败`)
      // 取消后，进行恢复按钮
      row.status = row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
    }
  } catch (e){
    console.log(e)
    // 取消后，进行恢复按钮
    row.status = row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 处理封禁/解封账户 */
const handleBanAccount = async (row: AccountBalanceVO) => {
  console.log('handleBanAccount called', row)
  try {
    const isCurrentlyActive = row.status === 0
    const action = isCurrentlyActive ? '封禁' : '解封'
    const newStatus = isCurrentlyActive ? 1 : 0
    
    // 封禁/解封的二次确认
    await message.confirm(`确认要${action}该账户吗？${isCurrentlyActive ? '封禁后该账户将无法正常使用。' : ''}`)
    
    debugger
    // 发起封禁/解封请求
    const res = await AccountBalanceApi.updateAccountBalanceStatus(row.id, newStatus)
    
    if (res) {
      // 刷新列表
      await getList()
    } else {
      message.error('操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AccountBalanceApi.exportAccountBalance(queryParams)
    download.excel(data, '账户余额.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 绑定抖音账号相关 */
const bindDialogVisible = ref(false)
const bindLoading = ref(false)
const bindFormRef = ref()
const bindForm = reactive({
  id: undefined as number | undefined,
  merchantId: undefined as number | undefined,
  advertiserId: ''
})

const bindRules = reactive({
  advertiserId: [{ required: true, message: '巨量账户ID不能为空', trigger: 'blur' }]
})

/** 催款相关 */
const dunningDialogVisible = ref(false)
const dunningLoading = ref(false)
const dunningFormRef = ref()
const currentAccount = ref<AccountBalanceVO | null>(null)
const dunningForm = reactive({
  accountId: undefined as number | undefined,
  merchantId: undefined as number | undefined,
  dunningType: 1, // 默认短信通知
  content: ''
})

const dunningRules = reactive({
  dunningType: [{ required: true, message: '请选择催款方式', trigger: 'change' }],
  content: [{ required: true, message: '请输入催款内容', trigger: 'blur' }]
})

/** 查询余额相关 */
const balanceDialogVisible = ref(false)
const balanceLoading = ref(false)
const balanceData = ref<JuliangBalanceVO | null>(null)

/** 查询日流水相关 */
const dailyFlowDialogVisible = ref(false)
const dailyFlowLoading = ref(false)
const dailyFlowFormRef = ref()
const dailyFlowData = ref({ list: [], total: 0 })
const dailyFlowForm = reactive({
  accountId: '',
  startDate: '',
  endDate: '',
  accountType: 'AD',
  page: 1,
  pageSize: 10
})

const dailyFlowRules = reactive({
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
})

/** 查询交易明细相关 */
const transactionDialogVisible = ref(false)
const transactionLoading = ref(false)
const transactionFormRef = ref()
const transactionData = ref({ list: [], total: 0 })
const transactionForm = reactive({
  accountId: '',
  startDate: '',
  endDate: '',
  transactionType: '',
  page: 1,
  pageSize: 10
})

const transactionRules = reactive({
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
})

/** 打开绑定抖音账号弹窗 */
const openBindDialog = (row: AccountBalanceVO) => {
  bindForm.id = row.id
  bindForm.merchantId = row.merchantId
  bindForm.advertiserId = (row as any).advertiserId || ''
  bindDialogVisible.value = true
}

/** 处理绑定抖音账号 */
const handleBind = async () => {
  // 校验表单
  await bindFormRef.value.validate()
  // 提交请求
  bindLoading.value = true
  try {
    // 构造更新数据，包含 merchantId 和 advertiserId
    const updateData = {
      id: bindForm.id,
      merchantId: bindForm.merchantId,
      advertiserId: bindForm.advertiserId
    }
    await AccountBalanceApi.updateAccountBalance(updateData as unknown as AccountBalanceVO)
    message.success('绑定巨量账号成功')
    bindDialogVisible.value = false
    // 刷新列表
    await getList()
  } finally {
    bindLoading.value = false
  }
}

/** 打开催款弹窗 */
const openDunningDialog = (row: AccountBalanceVO) => {
  currentAccount.value = row
  dunningForm.accountId = row.id
  dunningForm.merchantId = row.merchantId
  dunningForm.dunningType = 1
  dunningForm.content = `尊敬的商家，您的账户余额为${row.balance}元，已出现负余额。请及时充值以确保业务正常运行。如有疑问，请联系客服。`
  dunningDialogVisible.value = true
}

/** 处理发送催款 */
const handleSendDunning = async () => {
  try {
    // 校验表单
    await dunningFormRef.value.validate()
    
    dunningLoading.value = true
    
    // 构造催款数据
    const dunningData = {
      accountId: dunningForm.accountId!,
      merchantId: dunningForm.merchantId!,
      dunningType: dunningForm.dunningType,
      content: dunningForm.content,
      balance: currentAccount.value?.balance || 0
    }
    
    // 调用催款API（这里假设有一个催款接口）
    await AccountBalanceApi.sendDunningNotice(dunningData)
    
    message.success('催款通知发送成功')
    dunningDialogVisible.value = false
    
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('发送催款失败:', error)
    message.error('发送催款失败，请重试')
  } finally {
    dunningLoading.value = false
  }
}

/** 处理查询命令 */
const handleQueryCommand = (command: string, row: AccountBalanceVO) => {
  switch (command) {
    case 'balance':
      handleQueryBalance(row)
      break
    case 'dailyFlow':
      handleQueryDailyFlow(row)
      break
    case 'transaction':
      handleQueryTransaction(row)
      break
  }
}

/** 处理操作命令 */
const handleActionCommand = (command: string, row: AccountBalanceVO) => {
  switch (command) {
    case 'dunning':
      openDunningDialog(row)
      break
    case 'ban':
    case 'unban':
      handleBanAccount(row)
      break
    case 'delete':
      handleDelete(row.id)
      break
  }
}

/** 处理查询余额 */
const handleQueryBalance = async (row: AccountBalanceVO) => {
  balanceDialogVisible.value = true
  balanceLoading.value = true
  balanceData.value = null
  
  try {
    const params = {
      accountId: row.id,
      getJuliangBalance: false
    }
    const result = await AccountBalanceApi.getJuliangBalance(params)
    balanceData.value = result
  } catch (error) {
    console.error('查询余额失败:', error)
    message.error('查询余额失败，请重试')
  } finally {
    balanceLoading.value = false
  }
}

/** 处理查询日流水 */
const handleQueryDailyFlow = (row: AccountBalanceVO) => {
  dailyFlowForm.accountId = row.id.toString()
  // 设置默认日期范围（当前年份1月1日到今天）
  const currentYear = new Date().getFullYear()
  dailyFlowForm.startDate = `${currentYear}-01-01`
  dailyFlowForm.endDate = new Date().toISOString().split('T')[0]
  dailyFlowData.value = { list: [], total: 0 }
  dailyFlowDialogVisible.value = true
}

/** 查询日流水数据 */
const queryDailyFlow = async () => {
  try {
    await dailyFlowFormRef.value.validate()
    dailyFlowLoading.value = true
    
    const params = {
      accountId: dailyFlowForm.accountId,
      startDate: dailyFlowForm.startDate,
      endDate: dailyFlowForm.endDate,
      accountType: dailyFlowForm.accountType,
      page: dailyFlowForm.page,
      pageSize: dailyFlowForm.pageSize
    }
    
    const result = await AccountBalanceApi.getJuliangFundDailyStatFlow(params)
    dailyFlowData.value.list = result.list || []
    dailyFlowData.value.total = result.total || 0
  } catch (error) {
    console.error('查询日流水失败:', error)
    message.error('查询日流水失败，请重试')
  } finally {
    dailyFlowLoading.value = false
  }
}

/** 重置日流水表单 */
const resetDailyFlowForm = () => {
  const currentYear = new Date().getFullYear()
  dailyFlowForm.startDate = `${currentYear}-01-01`
  dailyFlowForm.endDate = new Date().toISOString().split('T')[0]
  dailyFlowForm.accountType = 'AD'
  dailyFlowForm.page = 1
  dailyFlowForm.pageSize = 10
  dailyFlowData.value = { list: [], total: 0 }
}

/** 处理查询交易明细 */
const handleQueryTransaction = (row: AccountBalanceVO) => {
  transactionForm.accountId = row.id.toString()
  // 设置默认日期范围（最近30天）
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  
  transactionForm.startDate = startDate.toISOString().split('T')[0]
  transactionForm.endDate = endDate.toISOString().split('T')[0]
  transactionForm.transactionType = 'RECHARGE' // 默认选择充值
  transactionData.value = { list: [], total: 0 }
  transactionDialogVisible.value = true
}

/** 查询交易明细数据 */
const queryTransaction = async () => {
  try {
    await transactionFormRef.value.validate()
    
    // 检查日期范围是否超过31天
    const startDate = new Date(transactionForm.startDate)
    const endDate = new Date(transactionForm.endDate)
    const diffTime = Math.abs(endDate.getTime() - startDate.getTime())
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    
    if (diffDays > 31) {
      message.error('查询时间范围不能超过31天，请重新选择日期范围')
      return
    }
    
    transactionLoading.value = true
    
    const params = {
      accountId: transactionForm.accountId,
      startDate: transactionForm.startDate,
      endDate: transactionForm.endDate,
      transactionType: transactionForm.transactionType,
      page: transactionForm.page,
      pageSize: transactionForm.pageSize
    }
    
    const result = await AccountBalanceApi.getJuliangTransactionRecord(params)
    transactionData.value.list = result?.list || []
    transactionData.value.total = result?.total || 0
  } catch (error) {
    console.error('查询交易明细失败:', error)
    message.error('查询交易明细失败，请重试')
  } finally {
    transactionLoading.value = false
  }
}

/** 重置交易明细表单 */
const resetTransactionForm = () => {
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  
  transactionForm.startDate = startDate.toISOString().split('T')[0]
  transactionForm.endDate = endDate.toISOString().split('T')[0]
  transactionForm.transactionType = 'RECHARGE' // 默认选择充值
  transactionForm.page = 1
  transactionForm.pageSize = 10
  transactionData.value = { list: [], total: 0 }
}

/** 日流水分页 */
const handleDailyFlowPagination = (page: number, pageSize: number) => {
  dailyFlowForm.page = page
  dailyFlowForm.pageSize = pageSize
  queryDailyFlow()
}
/** 交易明细分页 */
const handleTransactionPagination = (page: number, pageSize: number) => {
  transactionForm.page = page
  transactionForm.pageSize = pageSize
  queryTransaction()
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.merchant-select-content {
  .merchant-empty {
    padding: 20px;
    text-align: center;
  }
  
  .merchant-loading {
    padding: 8px 0;
    text-align: center;
    background-color: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color-lighter);
    
    .el-icon {
      margin-right: 6px;
      font-size: 16px;
      color: var(--el-color-primary);
      vertical-align: middle;
    }
    
    .loading-text {
      font-size: 13px;
      color: var(--el-text-color-secondary);
      vertical-align: middle;
    }
  }
}

:deep(.el-select-dropdown__wrap) {
  max-height: 300px;
}

:deep(.el-select-dropdown__list) {
  padding: 0;
}

// 负余额样式
.negative-balance {
  font-weight: bold;
  color: #f56c6c;
}

// 返利比例样式
:deep(.el-input-group__append) {
  color: var(--el-text-color-regular);
  background-color: var(--el-fill-color-light);
  border-left: 1px solid var(--el-border-color);
}

:deep(.el-form-item__content) {
  .el-input-group {
    width: 100%;
  }
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-form-item__error) {
  font-size: 12px;
  color: var(--el-color-danger);
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
  color: var(--el-color-danger);
}
</style>